#ifndef NETLIB_CONDITION_H
#define NETLIB_CONDITION_H

// 条件变量

#include "Mutex.h"

#include <pthread.h>

namespace netlib
{

class Condition : noncopyable // 不可拷贝
{
public:
    explicit Condition(MutexLock& mutex) : mutex_(mutex)
    { MCHECK(pthread_cond_init(&pcond_, NULL)); } // 构造初始化条件变量

    ~Condition() { MCHECK(pthread_cond_destroy(&pcond_)); } // 析构销毁条件变量

    void wait() // 等待
    {
        MutexLock::UnassignGuard ug(mutex_);
        MCHECK(pthread_cond_wait(&pcond_, mutex_.getPthreadMutex()));
    }

    bool waitForSeconds(double seconds);

    void notify() { MCHECK(pthread_cond_signal(&pcond_)); }

    void notifyAll() { MCHECK(pthread_cond_broadcast(&pcond_)); }

private:
    MutexLock& mutex_;          // 互斥锁的引用，不管理生命周期
    pthread_cond_t pcond_;      // 条件变量

};

} // namespace netlib end

#endif